package org.jeecg.modules.sggg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.SgFollowUp;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.entity.SgTreatmentAssist;
import org.jeecg.modules.sggg.service.ISgFollowUpService;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.sggg.service.ISgTreatmentAssistService;
import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Description: 随访表
 * @Author: jeecg-boot
 * @Date: 2022-10-27
 * @Version: V1.0
 */
@Api(tags = "随访表")
@RestController
@RequestMapping("/sggg/sgFollowUp")
@Slf4j
public class SgFollowUpController extends JeecgController<SgFollowUp, ISgFollowUpService> {
    @Autowired
    private ISgFollowUpService sgFollowUpService;

    @Autowired
    private ISgMemberService sgMemberService;
    @Autowired
    private ISgTreatmentAssistService sgTreatmentAssistService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysRoleController sysRoleController;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysDepartService sysDepartController;

    @Autowired
    private ISysUserService sysUserService;

    @ApiOperation(value = "随访表-分页列表查询", notes = "随访表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgFollowUp>> queryPageList(SgFollowUp sgFollowUp,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgFollowUp> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<SgFollowUp> pageList = sgFollowUpService.queryList(page, sgFollowUp.getName(), sgFollowUp.getIdCard(), sgFollowUp.getPhone(), sgFollowUp.getSysOrgCode(), sgFollowUp.getCheck(), sgFollowUp.getFollowUpDate(), sgFollowUp.getMemberId());
        return Result.OK(pageList);
    }


    /**
     * 随访记录查询（没有根据权限查询吗）
     *
     * @param sgMember 对象
     * @param pageNo   当前页
     * @param pageSize 页大小
     * @return 当前页数据
     */
    @ApiOperation(value = "随访表-随访记录查询", notes = "随访表-随访记录查询")
    @GetMapping(value = "/memberList")
    public Result<IPage<SgMember>> querymemberList(SgMember sgMember,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<SgMember> queryWrapper = new QueryWrapper<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.inSql("id", "select member_id FROM sg_follow_up");

        if (Strings.isNotBlank(sgMember.getId())) {
            queryWrapper.eq("id", sgMember.getId());
        }

        if (Strings.isNotBlank(sgMember.getName())) {
            queryWrapper.like("name", sgMember.getName());
        }

        if (Strings.isNotBlank(sgMember.getIdCard())) {
            queryWrapper.like("id_card", sgMember.getIdCard());
        }

        if (Strings.isNotBlank(sgMember.getPhone())) {
            queryWrapper.like("phone", sgMember.getPhone());
        }

        if (Strings.isNotBlank(sgMember.getSysOrgCode())) {
            if (Strings.isNotBlank(sgMember.getIsDown())) {
                queryWrapper.like("sys_org_code", sgMember.getSysOrgCode());
            } else {
                queryWrapper.eq("sys_org_code", sgMember.getSysOrgCode());
            }
        }
        //获取角色信息
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();

        if (Strings.isNotBlank(sgMember.getIsDown()) && Strings.isBlank(sgMember.getSysOrgCode())) {
            queryWrapper.like("sys_org_code", sysUser.getOrgCode());
        } else if (Strings.isNotBlank(sgMember.getSysOrgCode()) && Strings.isBlank(sgMember.getIsDown())) {
            // 选择了机构，没选择含下属
            if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
                queryWrapper.eq("sys_org_code", sgMember.getSysOrgCode());
            } else if (!roleCode.contains("admin")) {
                queryWrapper.eq("doctor_id", sysUser.getId());
            }
        } else if (Strings.isNotBlank(sgMember.getSysOrgCode()) && Strings.isNotBlank(sgMember.getIsDown())) {
            // 即选择了机构，又选择了含下属
            queryWrapper.like("sys_org_code", sgMember.getSysOrgCode());
        } else {
            // 超级管理员可以查看全部、机构管理员（医生）只查看本机构下、(机构管理员)
            if (!roleCode.contains("admin") && !roleCode.contains("dept_manage")) {
                SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
                SysUser sysUser1 = sysUserService.getById(sysUser.getId());
                // 判断当前登录人的所属机构
                if (sysDepart != null) {
                    // 根据部门表DeptAttr（机构属性）判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
                    if (sysDepart.getDeptAttr() != null && sysDepart.getDeptAttr().length() != 0) {
                        // 1.三高之家 村级
                        if (sysDepart.getDeptAttr().equals("1")) {
                            // 村医：查询自己所在的村以及自己所负责的居民
                            queryWrapper.and(wrapper -> wrapper.eq("sys_org_code",
                                    sysUser.getOrgCode()).or().eq("doctor_id", sysUser.getId().toString()));
                        }
                        // 2.三高基地 基地就是乡镇卫生院 不用根据负责的村室去查 直接查询本级以及下级机构的数据
                        else if (sysDepart.getDeptAttr().equals("2")) {
                            // 配置了所负责的村室
                            if(sysUser1.getResponsibleAgency()!=null){
                                String[] array = sysUser1.getResponsibleAgency().split(",");
                                List<String> responsibleAgencies = Arrays.asList(array);
                                queryWrapper.and(wrapper -> wrapper.in("sys_org_code", responsibleAgencies).
                                        or().eq("doctor_id", sysUser.getId().toString()));
                            }else{
                                queryWrapper.like("sys_org_code", sysUser.getOrgCode());
                            }
                        }
                        // 3.三高中心
                        else if (sysDepart.getDeptAttr().equals("3")) {
                            // 配置了所负责的村室
                            if(sysUser1.getResponsibleAgency()!=null){
                                String[] array = sysUser1.getResponsibleAgency().split(",");
                                List<String> responsibleAgencies = Arrays.asList(array);
                                queryWrapper.and(wrapper -> wrapper.in("sys_org_code",
                                        responsibleAgencies).or().eq("doctor_id", sysUser.getId().toString()));
                            }else{
                                queryWrapper.like("sys_org_code", sysUser.getOrgCode());
                            }
                        }
                    } else {
                        queryWrapper.eq("doctor_id", sysUser.getId().toString());
                    }
                } else {
                    // 当前登录的医生所属机构不是三高之家、三高基地、三高中心的，普通医生权限
                    if (sysUser1.getResponsibleAgency() != null) {
                        // 查询当前登录的医生所负责的村室的居民及当前登录的医生下的居民
                        String[] array = sysUser1.getResponsibleAgency().split(",");
                        List<String> responsibleAgencies = Arrays.asList(array);
                        queryWrapper.and(wrapper -> wrapper.in("sys_org_code", responsibleAgencies).or().eq("doctor_id", sysUser.getId().toString()));
                    } else {
                        // 查询当前登录的医生下的居民
                        queryWrapper.eq("doctor_id", sysUser.getId().toString());
                    }
                }
            }else{
                queryWrapper.like("sys_org_code", sysUser.getOrgCode());
            }
        }

        //SysRole role = sysRoleController.getUserRole(sysUser.getId()).getResult();
       /* List<SysRole> roleList = sysRoleService.getUserRole(sysUser.getId());
        String code = "";
        StringBuilder sb = new StringBuilder();
        for (SysRole role : roleList) {
            sb.append(role.getRoleCode());
            sb.append(",");
        }
        String sbstr = sb.toString();
        if (sbstr.contains("admin") ) {
            code = "admin";
        } else if (sbstr.contains("dept_manage")) {
            //机构管理员
            code = "dept_manage";
        } else {
            code = "other";
        }*/




        /*if (code.indexOf("admin") == -1 && code.indexOf("admin_") == -1) {

        } else if (code.indexOf("admin_") != -1) {

        }*/
        Page<SgMember> page = new Page<>(pageNo, pageSize);
        IPage<SgMember> pageList = sgMemberService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * xl ---- 居民信息管理 随访记录
     *
     * @param mid 居民id
     * @return 数据
     */
    @GetMapping(value = "/queryListByMid")
    public Result<List<SgFollowUp>> queryListByMid(String mid) {
        return Result.OK(sgFollowUpService.list(
                new QueryWrapper<SgFollowUp>()
                        .eq("member_id", mid)
                        .orderByDesc("create_time")
                        .select("id", "follow_up_date", "way", "bp_val", "dp_val", "height", "weight", "f_id")
        ));
    }

    /**
     * 添加
     *
     * @param sgFollowUp 对象
     * @return 结果
     */
    @AutoLog(value = "随访表-添加")
    @ApiOperation(value = "随访表-添加", notes = "随访表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgFollowUp sgFollowUp) {

        if (sgFollowUp.getReferral() == 1) {
            //协诊
            SgTreatmentAssist assist = new SgTreatmentAssist();
            assist.setMemberId(sgFollowUp.getMemberId());
            assist.setStatus(0);
            assist.setReason(sgFollowUp.getReferralMsg());
            sgTreatmentAssistService.save(assist);
        }
        sgFollowUpService.save(sgFollowUp);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "随访表-编辑")
    @ApiOperation(value = "随访表-编辑", notes = "随访表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgFollowUp sgFollowUp) {
        sgFollowUpService.updateById(sgFollowUp);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "随访表-通过id删除")
    @ApiOperation(value = "随访表-通过id删除", notes = "随访表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        sgFollowUpService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "随访表-批量删除")
    @ApiOperation(value = "随访表-批量删除", notes = "随访表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.sgFollowUpService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    @ApiOperation(value = "随访表-通过id查询", notes = "随访表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgFollowUp> queryById(@RequestParam(name = "id") String id) {
        SgFollowUp sgFollowUp = sgFollowUpService.getById(id);
        if (sgFollowUp == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgFollowUp);
    }

    //region WangJie 用于存取电子签名
    @ApiOperation(value = "电子签名存储", notes = "电子签名存储")
    @PostMapping(value = "/setSignature")
    public Result<String> SetSignature(@RequestBody SgFollowUp sgFollowUp) {
        redisUtil.set(sgFollowUp.getId() + "Yi", sgFollowUp.getSignatureImgYi(), 600);
        redisUtil.set(sgFollowUp.getId() + "Huan", sgFollowUp.getSignatureImgHuan(), 600);
        redisUtil.set(sgFollowUp.getId() + "follow", sgFollowUp.getFollowImg(), 600);
        return Result.OK("签名成功!");
    }

    @ApiOperation(value = "电子签名读取", notes = "电子签名读取")
    @GetMapping(value = "/getSignature")
    public Result<Map<String, Object>> GetSignature(String id) {
        Object SignatureImgYi = redisUtil.get(id + "Yi");
        Object SignatureImgHuan = redisUtil.get(id + "Huan");
        Object followImg = redisUtil.get(id + "follow");
        Map<String, Object> List = new HashMap<>();
        List.put("SignatureImgYi", SignatureImgYi);
        List.put("SignatureImgHuan", SignatureImgHuan);
        List.put("followImg", followImg);

        if (SignatureImgYi != null || SignatureImgHuan != null) {
            return Result.OK(List);
        }
        return Result.error("500");
    }


    /**
     * 随访表单-最后一次随访数据
     */
    @ApiOperation(value = "随访表单-最后一次随访数据", notes = "随访表单-最后一次随访数据")
    @GetMapping(value = "/followForm")
    public Result<SgFollowUp> FollowForm(@RequestParam(name = "id") String id) {
        return Result.OK(this.sgFollowUpService.getOne(
                new QueryWrapper<SgFollowUp>().eq("member_id", id).orderByDesc("create_time").last("limit 1")
        ));
    }

    /**
     * 查询某个用户所有的随访表单列表
     *
     * @return 列表
     * @author WangJie
     * @date 2022/11/25 10:55
     */
    @ApiOperation(value = "随访表单-查询某个用户所有的随访表单列表", notes = "随访表单-查询某个用户所有的随访表单列表")
    @GetMapping(value = "/queryListById")
    public Result<List<SgFollowUp>> queryForm(@RequestParam(name = "id") String id) {
        QueryWrapper<SgFollowUp> server = new QueryWrapper<>();
        server.eq("member_id", id).orderByDesc("create_time").select("create_time", "id");
        List<SgFollowUp> data = sgFollowUpService.list(server);
        return Result.OK(data);
    }
}
